﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MaterialTextureAnimation : MonoBehaviour {


    public enum EPlayModeEnum
    {
        None,
        Loop,
        Once,
    }
    public EPlayModeEnum playMode;

    public bool playOnStart = false;

    //private List<string> textureList = new List<string>();

    public Texture defaultTexture;
    public List<Texture> textureList = new List<Texture>();

    public float intervalTime = 0.1f;

    private bool bPlaying;
    private float addTime;
    private int index;


    private MeshRenderer _meshRenderer;
    public MeshRenderer meshRenderer
    {
        get
        {
            if (_meshRenderer == null)
            {
                _meshRenderer = GetComponentInChildren<MeshRenderer>();
            }

            return _meshRenderer;
        }
    }

    private void Start()
    {
        if (playOnStart)
            Play(playMode);
    }

    private void Update()
    {
        if (bPlaying)
        {
            switch (playMode)
            {
                case EPlayModeEnum.Loop:
                case EPlayModeEnum.Once:
                    addTime += Time.deltaTime;
                    if (addTime > intervalTime)
                    {
                        addTime = 0;
                        MoveToNextTexture();
                    }
                    break;
            }
        }
    }

    public void Play(EPlayModeEnum mode)
    {
        playMode = mode;
        bPlaying = true;
    }

    public void Stop()
    {
        bPlaying = false;
        meshRenderer.material.SetTexture("_MainTex", defaultTexture);
    }

    private void MoveToNextTexture()
    {
        if (index >= textureList.Count)
        {
            index = 0;
            if (playMode == EPlayModeEnum.Once)
            {
                playMode = EPlayModeEnum.None;
                return;
            }
        }

        Texture texture = textureList[index];
        meshRenderer.material.SetTexture("_MainTex", texture);

        index++;
    }


    //public void InitAnimation(List<string> textureNames, float intervalTime)
    //{
    //    this.intervalTime = intervalTime;
    //    textureList = textureNames;
    //    if()

    //}



}
